Button
In Windows Forms we use a Button
control that accepts click events and performs other actions in the user interface. This control provides a way to accept input.
In Visual Studio, go to the View menu and select the Toolbox option. Locate the Button
item in the Toolbox window and either double-click it or drag it to your window.
We see the body of the Click event that can be added to handle click events for the button1 control instance. You do not need to type in button1_Click
.
MessageBox.Show
method call to perform a trivial action when the event is processed.Button
control.using System;
using System.Windows.Forms;
namespace WindowsFormsApplication21
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Dot Net Perls says hello.",
"How is your day going?");
}
}
}
Windows Forms programs are event-based. When you add a Click event handler to a Button
, the event handler method will be invoked when the user clicks on the button.
private void button1_Click(object sender, EventArgs e)
{
// Created when the Click event handler is selected.
}
In this window, a lightning bolt signifies the event handlers list. You can click on it and then double-click on an event. The C# code will then be inserted.
By specifying the constraints of your Button
, you can avoid modifying pixel dimensions. You should experiment with the Anchor property to control the resizing of the Button
.
TableLayoutPanel
cells, as this reduces the need to position them manually.We explored the Button
control in the Windows Forms control set. We added a new instance of the Button
control. We next changed the appearance of the Button
control and its text.